<template>
  <div class="login-box">
    <div class="login-box-center">
      <a-form :rules="rules" ref="formData" :model="formState">
        <a-form-item name="username">
          <a-input v-model:value="formState.username" placeholder="Username">
          </a-input>
        </a-form-item>
        <a-form-item name="password">
          <a-input v-model:value="formState.password" placeholder="Password">
          </a-input>
        </a-form-item>
        <a-form-item name="code">
          <div class="code-box-center">
            <a-input
              v-model:value="formState.code"
              placeholder="Code"
            ></a-input>
            <div 
              class="title-code" 
              v-html="codeHtml"
              @click="getCode"
            ></div>
          </div>
        </a-form-item>
        <a-form-item>
          <a-button @click="onSubmit" type="primary">登录</a-button>
          <a-button style="margin-left: 20px" @click="onReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
 
<script setup>
import axios from "axios";
import { reactive, ref, toRaw, onMounted } from "vue";
import {useRouter} from "vue-router"
import { message } from 'ant-design-vue';
const formData = ref(null);
const codeHtml = ref("");
const $router = useRouter()
const formState = reactive({
  username: "",
  password: "",
  code: "",
});
const rules = {
  username: {
    required: true,
    message: "请输入账号",
  },
  password: {
    required: true,
    message: "请输入密码",
  },
  code: {
    required: true,
    message: "请输入验证码",
  },
};
const onSubmit = () => {
  formData.value
    .validate()
    .then(() => {
      axios.post("/api/login", formState).then((v) => {
        console.log(v);
        if(!v.data.errcode){
            message.success('登录成功');
            setTimeout(()=>{
                $router.push('/about')
            },1000)
        }else{
          if(v.data.errmsg=='验证码错误'){
            getCode()
          }
          message.error(v.data.errmsg);
        }
      });
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const onReset = () =>{
    formState.password = '',
    formState.username = ''
    formState.code = ''
}
const getCode = () => {
  axios.get("/api/captcha").then((v) => {
    if (!v.data.errcode) {
      codeHtml.value = v.data.data;
    }
  });
};
onMounted(() => {
    getCode()
});
</script>
 
<style scoped lang="sass">
.login-box-center
    position: fixed
    width: 400px
    height: 300px
    background: #ccc
    padding: 20px
    left: 50%
    top: 50%
    transform: translate(-50%,-50%)
    border-radius: 17px
    background: #b7c4f5
    box-shadow: inset 33px 33px 66px #b7c4f5,inset -33px -33px 66px #b7c4f5
    .code-box-center
        display: flex
        height: 40px
        justify-content: space-between
        align-items: center
        input
            width: 180px
</style>